import base64
import json
import random

from django.conf import settings

from libs.yuntongxun.sms import CCP
from worker import celery_app
from django_redis import get_redis_connection
import hashlib


# 把django中第三方或者耗时的方法变成celery中的任务
@celery_app.task
def send_sms(phone):
    ccp = CCP()

    sms_code = create_sms_code(4)

    # 把验证码存储redis的缓存中
    redis_cli = get_redis_connection()
    redis_cli.set(f'smscode-{phone}', sms_code, 18000)



    ccp.send_template_sms(phone, [sms_code, 3], 1)


def create_sms_code(num):

    start = 10 ** (num - 1)
    end = 10 ** num - 1

    return random.randint(start, end)





def create_token(phone):

    # 第一部分头信息
    # 申明类型,和加密方式
    part1 = {'type': 'jwt', 'alg': 'hs256'}
    part1_base64 = base64.b64encode(json.dumps(part1).encode()).decode()

    # 第二部分是载荷
    part2 = {'phone': phone}
    part2_base64 = base64.b64encode(json.dumps(part2).encode()).decode()

    # 第三部分是签证,是用来生成和验证token的数据
    part3 = part1_base64 + '.' + part2_base64 + settings.SECRET_KEY
    sha256 = hashlib.sha256()
    sha256.update(part3.encode())
    part3_sha256 = sha256.hexdigest()

    token = part1_base64 + '.' + part2_base64 + '.' + part3_sha256

    return token


def check_token(token):

    data = token.split('.')

    new_part3 = data[0] + '.' + data[1] + settings.SECRET_KEY

    sha256 = hashlib.sha256()
    sha256.update(new_part3.encode())
    sign = sha256.hexdigest()


    payload = json.loads(base64.b64decode(data[1].encode()))
    phone = payload.get('phone')


    if sign == data[2]:
        return True, phone
    else:
        return False, phone

